<template>
  <view class="container">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-box">
        <input 
          type="text" 
          v-model="searchKeyword" 
          placeholder="搜索商品" 
          confirm-type="search"
          @confirm="handleSearch"
          @input="handleInput"
          class="search-input"
        />
        <text class="clear-icon" v-if="searchKeyword" @click="clearSearch">×</text>
      </view>
      <text class="cancel-btn" @click="goBack">取消</text>
    </view>

    <!-- 搜索建议 -->
    <view class="search-suggestions" v-if="showSuggestions && searchKeyword">
      <view 
        class="suggestion-item" 
        v-for="(item, index) in searchSuggestions" 
        :key="index"
        @click="selectSuggestion(item)"
      >
        <text class="suggestion-icon">🔍</text>
        <text class="suggestion-text">{{ item }}</text>
      </view>
    </view>

    <!-- 搜索历史 -->
    <view class="search-history" v-if="!searchKeyword && searchHistory.length > 0">
      <view class="section-header">
        <text class="section-title">搜索历史</text>
        <text class="clear-history" @click="clearHistory">清空历史</text>
      </view>
      <view class="history-tags">
        <text 
          class="history-tag" 
          v-for="(item, index) in searchHistory" 
          :key="index"
          @click="searchWithKeyword(item)"
        >{{ item }}</text>
      </view>
    </view>

    <!-- 热门搜索 -->
    <view class="hot-search" v-if="!searchKeyword">
      <view class="section-header">
        <text class="section-title">热门搜索</text>
      </view>
      <view class="hot-tags">
        <text 
          class="hot-tag" 
          v-for="(item, index) in hotSearches" 
          :key="index"
          @click="searchWithKeyword(item)"
        >{{ item }}</text>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-results" v-if="hasSearched">
      <!-- 筛选栏 -->
      <view class="filter-bar">
        <view 
          class="filter-item" 
          :class="{ active: currentSort === 'default' }"
          @click="changeSort('default')"
        >综合</view>
        <view 
          class="filter-item" 
          :class="{ active: currentSort === 'sales' }"
          @click="changeSort('sales')"
        >销量</view>
        <view 
          class="filter-item price-sort" 
          :class="{ active: currentSort.startsWith('price') }"
          @click="changePriceSort"
        >
          价格
          <text class="sort-arrow" v-if="currentSort === 'price-asc'">↑</text>
          <text class="sort-arrow" v-if="currentSort === 'price-desc'">↓</text>
        </view>
      </view>

      <!-- 结果列表 -->
      <view class="result-list" v-if="searchResults.length > 0">
        <view 
          class="result-item" 
          v-for="(item, index) in searchResults" 
          :key="index"
          @click="navigateToDetail(item)"
        >
          <image :src="item.image" mode="aspectFill" class="item-image"></image>
          <view class="item-info">
            <text class="item-name">{{ item.name }}</text>
            <text class="item-price">¥{{ item.price }}</text>
            <text class="item-sales">已售{{ item.sales }}件</text>
          </view>
        </view>
      </view>

      <!-- 无结果提示 -->
      <view class="no-result" v-else>
        <image src="/static/images/no-result.png" mode="aspectFit" class="no-result-image"></image>
        <text class="no-result-text">未找到相关商品</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: '',
      searchHistory: [],
      hotSearches: ['新鲜水果', '时令蔬菜', '农家土鸡', '有机大米', '土特产', '山珍'],
      searchSuggestions: [],
      showSuggestions: false,
      hasSearched: false,
      searchResults: [],
      currentSort: 'default',
      // 模拟的商品数据
      allProducts: [
        {
          id: '1',
          name: '新鲜苹果',
          price: 5.9,
          image: '/static/images/products/apple.jpg',
          sales: 1000,
          category: '水果'
        },
        {
          id: '2',
          name: '有机胡萝卜',
          price: 3.9,
          image: '/static/images/products/carrot.jpg',
          sales: 800,
          category: '蔬菜'
        }
        // 可以添加更多商品
      ]
    }
  },
  onLoad() {
    // 加载搜索历史
    this.loadSearchHistory()
  },
  methods: {
    loadSearchHistory() {
      const history = uni.getStorageSync('searchHistory')
      if (history) {
        this.searchHistory = JSON.parse(history)
      }
    },
    saveSearchHistory() {
      // 将当前关键词添加到历史记录
      if (!this.searchKeyword) return
      
      let history = this.searchHistory
      // 删除已存在的相同关键词
      const index = history.indexOf(this.searchKeyword)
      if (index !== -1) {
        history.splice(index, 1)
      }
      // 添加到开头
      history.unshift(this.searchKeyword)
      // 限制历史记录数量
      if (history.length > 10) {
        history = history.slice(0, 10)
      }
      
      this.searchHistory = history
      uni.setStorageSync('searchHistory', JSON.stringify(history))
    },
    clearHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清空搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            this.searchHistory = []
            uni.setStorageSync('searchHistory', '[]')
          }
        }
      })
    },
    handleInput() {
      // 实时搜索建议
      if (this.searchKeyword) {
        this.showSuggestions = true
        // 模拟搜索建议
        this.searchSuggestions = this.allProducts
          .filter(item => item.name.includes(this.searchKeyword))
          .map(item => item.name)
          .slice(0, 5)
      } else {
        this.showSuggestions = false
        this.hasSearched = false
      }
    },
    handleSearch() {
      if (!this.searchKeyword) return
      
      this.showSuggestions = false
      this.hasSearched = true
      this.saveSearchHistory()
      
      // 执行搜索
      this.searchResults = this.allProducts.filter(item => 
        item.name.includes(this.searchKeyword) ||
        item.category.includes(this.searchKeyword)
      )
      
      this.sortResults()
    },
    searchWithKeyword(keyword) {
      this.searchKeyword = keyword
      this.handleSearch()
    },
    selectSuggestion(suggestion) {
      this.searchKeyword = suggestion
      this.handleSearch()
    },
    clearSearch() {
      this.searchKeyword = ''
      this.showSuggestions = false
      this.hasSearched = false
    },
    goBack() {
      uni.navigateBack()
    },
    changeSort(sort) {
      this.currentSort = sort
      this.sortResults()
    },
    changePriceSort() {
      if (this.currentSort === 'price-asc') {
        this.currentSort = 'price-desc'
      } else {
        this.currentSort = 'price-asc'
      }
      this.sortResults()
    },
    sortResults() {
      switch (this.currentSort) {
        case 'sales':
          this.searchResults.sort((a, b) => b.sales - a.sales)
          break
        case 'price-asc':
          this.searchResults.sort((a, b) => a.price - b.price)
          break
        case 'price-desc':
          this.searchResults.sort((a, b) => b.price - a.price)
          break
        default:
          // 综合排序，按照相关度（包含关键词的优先）和销量的综合考虑
          this.searchResults.sort((a, b) => {
            const aRelevance = a.name.includes(this.searchKeyword) ? 1 : 0
            const bRelevance = b.name.includes(this.searchKeyword) ? 1 : 0
            return bRelevance - aRelevance || b.sales - a.sales
          })
      }
    },
    navigateToDetail(item) {
      uni.navigateTo({
        url: `/pages/spxq/detail?productInfo=${encodeURIComponent(JSON.stringify(item))}`
      })
    }
  }
}
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f0fff0;
  border-radius: 30rpx;
  padding: 0 20rpx;
  margin-right: 20rpx;
  height: 60rpx;
}

.search-input {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
}

.clear-icon {
  padding: 0 10rpx;
  color: #999;
  font-size: 40rpx;
}

.cancel-btn {
  font-size: 28rpx;
  color: #4CAF50;
}

.search-suggestions {
  background-color: #fff;
}

.suggestion-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.suggestion-icon {
  margin-right: 20rpx;
  font-size: 28rpx;
}

.suggestion-text {
  font-size: 28rpx;
  color: #333;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 20rpx;
}

.section-title {
  font-size: 30rpx;
  color: #333;
  font-weight: bold;
}

.clear-history {
  font-size: 24rpx;
  color: #999;
}

.history-tags, .hot-tags {
  padding: 0 20rpx;
  display: flex;
  flex-wrap: wrap;
}

.history-tag, .hot-tag {
  padding: 10rpx 20rpx;
  background-color: #fff;
  border-radius: 30rpx;
  margin: 0 20rpx 20rpx 0;
  font-size: 24rpx;
  color: #666;
}

.hot-tag {
  background-color: #f0fff0;
  color: #4CAF50;
}

.filter-bar {
  display: flex;
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.filter-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.filter-item.active {
  color: #4CAF50;
  font-weight: bold;
}

.price-sort {
  display: flex;
  align-items: center;
  justify-content: center;
}

.sort-arrow {
  margin-left: 6rpx;
}

.result-list {
  padding: 20rpx;
}

.result-item {
  display: flex;
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
}

.item-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 28rpx;
  color: #333;
}

.item-price {
  font-size: 32rpx;
  color: #4CAF50;
  font-weight: bold;
}

.item-sales {
  font-size: 24rpx;
  color: #999;
}

.no-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 200rpx;
}

.no-result-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.no-result-text {
  font-size: 28rpx;
  color: #999;
}
</style> 